package com.atguigu.tingshu.live.service.impl;

import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.live.mapper.LiveRoomMapper;
import com.atguigu.tingshu.live.service.LiveRoomService;
import com.atguigu.tingshu.live.util.LiveAutoAddressUtil;
import com.atguigu.tingshu.model.live.LiveRoom;
import com.atguigu.tingshu.vo.live.LiveRoomVo;
import com.atguigu.tingshu.vo.live.TencentLiveAddressVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class LiveRoomServiceImpl extends ServiceImpl<LiveRoomMapper, LiveRoom> implements LiveRoomService {

	@Autowired
	private LiveRoomMapper liveRoomMapper;

	@Override
	public LiveRoom getCurrentLive() {
		Long userId = AuthContextHolder.getUserId();
		return liveRoomMapper.selectOne(new LambdaQueryWrapper<LiveRoom>().eq(LiveRoom::getUserId,userId).gt(LiveRoom::getExpireTime,new Date()));
	}

	@Override
	public LiveRoom saveLiveRoom(LiveRoomVo liveRoomVo) {
		Long userId = AuthContextHolder.getUserId();
		LiveRoom liveRoom = new LiveRoom();
		liveRoom.setUserId(userId);
		liveRoom.setCoverUrl(liveRoomVo.getCoverUrl());
		liveRoom.setLiveTitle(liveRoomVo.getLiveTitle());
		liveRoom.setViewCount(0);
		liveRoom.setStatus("1");
		liveRoom.setTagId(liveRoomVo.getTagId());
		liveRoom.setExpireTime(liveRoomVo.getExpireTime());
		liveRoom.setLongitude(liveRoomVo.getLongitude());
		liveRoom.setLatitude(liveRoomVo.getLatitude());
		liveRoom.setLocation(liveRoomVo.getLocation());
		String streamName = "live:".concat(userId.toString());
		long time = liveRoom.getExpireTime().getTime();
		long exTime = time / 1000;
		TencentLiveAddressVo addressUrl = LiveAutoAddressUtil.getAddressUrl(streamName, exTime);
		liveRoom.setAppName("live");
		liveRoom.setStreamName(streamName);
		liveRoom.setPushUrl(addressUrl.getPushWebRtcUrl());
		liveRoom.setPlayUrl(addressUrl.getPullFlvUrl());

		liveRoomMapper.insert(liveRoom);
		return liveRoom;
	}

	@Override
	public List<LiveRoom> findLiveList() {
		return liveRoomMapper.selectList(new LambdaQueryWrapper<LiveRoom>().gt(LiveRoom::getExpireTime,new Date()));
	}
}
